//index.js 进入app 的 第一页
//获取应用实例
const app = getApp()
import { request } from '../../utils/util'
const { $Message } = require('../../dist/base/index');

Page({
  data: {
    visible: false, //微信登陆账号不存在的提示modal
    actions: [       //modal上的按钮
      {
        name: '取消'
      },
      {
        name: '如何获取',
        color: '#2d8cf0',
      },
      {
        name: '已有账号',
        color: '#19be6b'
      },


    ],
    code: "", //保存onshow里的login code
    isLoading: false //控制微信登陆不能多次点击
  },
  /**
   * 生命周期，显示的时候进行
   * 1 进行一次请求，若本地存在信息则登陆
   * 2 进行一次login()获取code，解决微信登陆的bug
   */
  onShow() {
    const that = this;
    //解决第一次登录后没选公司返回首页，自动登陆的问题
    const isNeedClearStorage = wx.getStorageSync('choiceOrg') || false
    if (isNeedClearStorage) {
      wx.clearStorageSync();
    }
    //----------------------------------------------------------------------
    const header = {
      'location': "org",
      'cookie': "csrftoken=" + wx.getStorageSync('csrf') + ";" + wx.getStorageSync('sessionid'),
    }
    wx.request({
      url: `${app.globalData.host}/api/service/catalog/?type=org`,
      header: header,
      success: res => {
        if (res.statusCode === 200) {
          wx.switchTab({
            url: '/pages/tabBar/search/search',
          })
        } else {
          return
        }
      }
    })
    wx.login({
      success: res => {
        that.setData({
          ...that.data,
          code: res.code
        })
      }
    })
  },
  /**
   * 微信用户一键登录
   * @param {*} e 
   */
  bindGetUserInfo(e) {
    if (this.data.isLoading === true) { //防止多次点击，导致报错
      return
    }
    this.setData({
      isLoading:true
    })
    const that = this
    wx.getUserProfile({
      desc: '用于标识个人头像',
      success: res => {
        console.log(res)
        const userRes = res
        const data = {
          code: that.data.code
        }
        request("GET", "/api/auth/wx/", data, "", true, "正在登录")
          .then(res => {
            if (res.data.errcode === 40029 || res.data.errcode === 40163) {
              $Message({
                content: '调用第三方服务失败，请稍后再试',
                type: 'warning',
                durtion: 1
              });
              that.setData({
                ...that.data,
                isLoading: false
              })
              that.onShow();
              return
            }
            if (res.data.token) {
              const data = {
                data: userRes
              }
              request("POST", `/api/auth/wx/?token=${res.data.token}`, data, "", true, "登录中").then(res => {
                if (res.statusCode === 200) {
                  that.setData({
                    ...that.data,
                    isLoading: false
                  })
                  if (res.data.code === 421) {

                    that.handleOpen();
                  } else if (res.data.code === 420) {

                    $Message({
                      content: '调用第三方服务失败，请稍后再试',
                      type: 'warning',
                      durtion: 2
                    });
                  } else {


                    const csrf = res.cookies[0] || ""
                    const sessionId = res.cookies[1] || ""
                    const a = csrf.split(";")[0]
                    const b = a.split("=")[1]
                    const b_name = a.split("=")[0]
                    const c = sessionId.split(";")[0]
                    const d = c.split("=")[1]
                    const d_name = c.split("=")[0]
                    if (b_name === "csrftoken") {
                      wx.setStorageSync('csrf', b)
                    } else {
                      wx.setStorageSync('csrf', d)
                    }
                    wx.setStorageSync(b_name, b_name + "=" + b)
                    wx.setStorageSync(d_name, d_name + "=" + d)
                    wx.setStorageSync('userInfo', res.data.userInfo)
                    if (res.data.userInfo.org_list) {
                      const param = {
                        username: res.data.userInfo.phone,
                        org_list: res.data.userInfo.org_list
                      }
                      wx.navigateTo({
                        url: `/pages/components/OrgChoice/orgChoic?param=${JSON.stringify(param)}`,
                      })
                    } else {
                      wx.setStorageSync('userInfo', res.data.userInfo)
                      wx.switchTab({
                        url: '/pages/tabBar/search/search',
                      })
                    }



                  }
                } else {
                  that.setData({
                    ...that.data,
                    isLoading: false
                  })
                  $Message({
                    content: '服务器错误，请稍后再试',
                    type: 'warning'
                  });
                }
              }).catch(res => {
              })
            } else {
              that.setData({
                isLoading:false
              })
              return
            }
          }
          )
      },
      fail: res => {
        that.setData({
          isLoading:false
        })
        return
      }
    })
  },
  /**
     * 手机账号密码登录
     */
  phoneLogin(e) {
    wx.navigateTo({
      url: '../login/login',
      success: res => {
      },
      fail: res => {
      }
    })
  },
  /**
   * 两个协议
   */
  consumer(e) {
    wx.navigateTo({
      url: '../webView/consumer/consumer',
      success: res => {
      }
    })
  },
  privacy(e) {
    wx.navigateTo({
      url: '../webView/privacy/privacy',
      success: res => {
      }
    })
  },
  /**
   * modal功能模块
   */
  handleOpen() {
    this.setData({
      visible: true
    });
  },
  /**
   * 当微信不存在账号时，弹出来的操作框的各种操作
   * @param {*} param0 
   */
  handleClick({ detail }) {
    const index = detail.index;
    if (index === 0) {
      this.setData({
        visible: false
      });
      this.onShow();
    } else if (index === 1) {
      wx.navigateTo({
        url: '../../components/Advertise/index',
      })
    } else {
      wx.navigateTo({
        url: '../login/login',
        success: res => {
        },
        fail: res => {
        }
      })
    }
  },
})
